﻿using QiuShiBaiKe.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QiuShiBaiKe.DAL
{
    public class UserDAL
    {
        private QiuShiBaiKe.Model.QiuShiBaiKeDBEntities entity;
        public UserDAL(QiuShiBaiKe.Model.QiuShiBaiKeDBEntities entity)
        {
            this.entity = entity;
        }

        /// <summary>
        /// 新增一个用户
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="passwordHash">密码的Hash值</param>
        /// <returns>如果用户名已经存在，则返回false</returns>
        public bool Insert(String userName, String passwordHash)
        {
            //在一个连接中
            bool isExists = entity.Users.Where(u => u.UserName == userName).Any();
            if (isExists)
            {
                return false;
            }
            else
            {
                User user = new User();
                user.UserName = userName;
                user.PasswordHash = passwordHash;
                entity.Users.Add(user);
                entity.SaveChanges();
                return true;
            }
        }

        /// <summary>
        /// 更新用户密码
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <param name="passwordHash">密码Hash值</param>
        public void Update(long id, String passwordHash)
        {
            User user = entity.Users.Where(u => u.Id == id).FirstOrDefault();
            if (user == null)
            {
                throw new Exception("根据id找不到对应的User");
            }
            user.PasswordHash = passwordHash;
        }

        /// <summary>
        /// 根据用户名查询用户信息
        /// </summary>
        /// <param name="userName">要查找的用户名</param>
        /// <returns></returns>
        public User GetByUserName(string userName)
        {
            User user = entity.Users.Where(u => u.UserName == userName).FirstOrDefault();
            return user;
        }

        /// <summary>
        /// 根据用户id查找用户对象
        /// </summary>
        /// <param name="id">用户id</param>
        /// <returns></returns>
        public User GetById(long id)
        {
            User user = entity.Users.Where(u => u.Id == id).FirstOrDefault();
            return user;
        }
    }
}
